/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import web.enity.Book;
import web.enity.Cart;
import web.enity.CartItem;
import web.enity.UserInfo;
import web.service.BookService;
import web.service.Impl.BookServiceImpl;
import web.service.Impl.OrderServiceImpl;
import web.service.OrderService;

/**
 *
 * @author 10592
 */
public class CartServlet extends HttpServlet {

    public static final String CART_KEY = "ShoppingCart";
    BookService bookService = new BookServiceImpl();
    OrderService orderService = new OrderServiceImpl();
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        //在session中取购物车实例，如果不存在则创建购物车实例，并放在session
        HttpSession session = request.getSession();
        //初始化orderService
        OrderService orderService = new OrderServiceImpl();
        Cart cart = (Cart) session.getAttribute(CART_KEY);
        if (cart == null) {
            cart = new Cart();
            session.setAttribute(CART_KEY, cart);
           
        }

        // 根据action进行不同的页面逻辑处理
        String action = request.getParameter("action");
        if ("add".equals(action)) {
            // 获取商品id
            String[] strbookid = request.getParameterValues("bookId");
            for (String string : strbookid) {
                Book book = bookService.getById(Integer.valueOf(string));
                cart.add(book);
                for (CartItem item : cart.getItems()) {
                    System.out.println(item.getBook().getBookName() + "\t" + item.getNumber());
                }
            }
            
            session.setAttribute(CART_KEY, cart);
            response.sendRedirect(request.getContextPath() + "/shopping.jsp");
        }  else if ("order".equals(action)) {
                UserInfo userInfo = (UserInfo) session.getAttribute("Login_USER");
            if (userInfo==null) {
                System.out.println("session已失效");
                request.getRequestDispatcher("login.jsp").forward(request, response);
            }else{
                cart.setUserInfo(userInfo);
                System.out.println(userInfo.getUserName());
                boolean placeorder=orderService.placeOrder(cart);
                if (placeorder) {
                    // 清空购物车
                    session.removeAttribute(CART_KEY);
                    response.sendRedirect(request.getContextPath() + "/shopping-success.html");
                } else {
                    request.setAttribute("error", "系统繁忙，请稍后重试！");
                    response.sendRedirect(request.getContextPath() + "/shopping.jsp");
                }
            }
           
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
